package com.ajk.shop.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ajk.server.exception.ErrorConstant;
import com.ajk.shop.dao.GoodsMapper;
import com.ajk.shop.dao.OrderMapper;
import com.ajk.shop.exception.ShopServerException;
import com.ajk.shop.model.Goods;
import com.ajk.shop.model.GoodsConstant;
import com.ajk.shop.model.ImputedPrice;
import com.ajk.shop.model.OrderConstant;
import com.ajk.shop.model.OrderDetail;
import com.ajk.shop.model.OrderInfo;
import com.ajk.shop.model.OrderInvoice;
import com.ajk.shop.model.PostageConfig;
import com.ajk.shop.model.UserAddress;
import com.ajk.shop.model.UserInvoice;
import com.ajk.shop.model.request.OrderInfoReq;
import com.ajk.shop.model.response.GoodsRes;
import com.ajk.shop.model.response.OrderDetailsRes;
import com.ajk.shop.model.response.OrderInfoRes;
import com.ajk.shop.model.response.UserDefaultAddressInvoice;
import com.ajk.shop.service.GoodsService;
import com.ajk.shop.service.OrderService;
import com.ajk.shop.service.UserAddressService;
import com.ajk.shop.utils.DateUtils;
import com.ajk.shop.utils.FileStoreUtil;
import com.ajk.shop.utils.StringUtil;


/** 
 * @author 作者 : chenxuan
 * @version 创建时间：2016年1月6日 上午9:38:29 
 * 类说明 
 */
@Service
public class OrderServiceImpl implements OrderService{


	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private UserAddressService userAddressService;
	@Autowired
	private GoodsMapper goodsMapper;

	@Override
	public OrderInfoRes createOrder(OrderInfoReq orderInfoReq) {
		if(orderInfoReq.getUserId() == null || orderInfoReq.getUserId() == 0){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "用户ID不能为空");
		}
		if(orderInfoReq.getOrderDetails() == null || orderInfoReq.getOrderDetails().isEmpty()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "商品ID不能为空");
		}
		//商品总购买数量 
		Integer goodsNumber = 0;
		//用户收货地址,如果有实体商品时会赋值
		UserAddress userAddress = null;
		String orderTitle = null;
		String orderImg = null;
		//是否有实体商品
		List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();
		//订单实体
		OrderInfoRes orderInfo = new OrderInfoRes();
		for(OrderDetail od : orderInfoReq.getOrderDetails()){
			OrderDetail orderDetail = new OrderDetail();
			boolean addressFlag = false;
			//订单类型
			if(od.getGoodsNumber() == null || od.getGoodsNumber() == 0){
				throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "购买数量不能为空");
			}
			goodsNumber += od.getGoodsNumber();
			Goods goods = goodsMapper.getGoodsDetailById(od.getGoodsId());
			// goodsService.goodsDetailById(od.getGoodsId());
			if(orderImg == null){
				orderImg = goods.getThumbnailImage();
			}
			if(goods == null){
				throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "该商品不存在");
			}
			orderTitle = goods.getTitle();
			/**
			if(goods.getIsOnsale() == 0){
				throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "该商品未上架");
			}
			 **/
			if(goods.getIsOnsale() == 2){
				throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "该商品已下架");
			}
			//检查库存 并扣减库存
			goodsService.subtractStock(od.getGoodsId(), od.getGoodsNumber());

			orderDetail.setGoodsId(goods.getId());//商品ID
			orderDetail.setGoodsName(goods.getTitle());//商品名称
			orderDetail.setSalePrice(goods.getSalePrice());//交易价格
			orderDetail.setGoodsNumber(od.getGoodsNumber());//购买数量
			Integer realPrice = (goods.getSalePrice() * od.getGoodsNumber());
			orderDetail.setRealPrice(realPrice);//该商品实际总价
			orderDetail.setMarketPrice(goods.getMarketPrice());//市场价

			//判断收货地址ID是否为空
			if(orderInfoReq.getUserAddressId() == null || orderInfoReq.getUserAddressId() ==0){
				throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "用户收货地址不能为空");
			}
			userAddress = userAddressService.getUserAddressById(orderInfoReq.getUserAddressId());
			if(userAddress == null ){
				throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "未查询到用户收货地址");
			}else{
				addressFlag = true;
			}
			orderDetail.setIsService(0);//服务
			orderDetail.setIsReal(1);//实体商品
			orderInfo.setGoodsType(goods.getGoodsType());

			orderDetails.add(orderDetail);
		}
		String orderNo = StringUtil.generateOrderNO();
		orderInfo.setOrderNo(orderNo);//订单编号
		orderInfo.setUserId(orderInfoReq.getUserId());
		orderInfo.setOrderStatus(OrderConstant.ORDER_STATUS_CONFIRMED.getOrderStatus());//订单状态 默认为已确认

		orderInfo.setReceiver(userAddress.getName());
		orderInfo.setProvince(userAddress.getProvince());
		orderInfo.setCity(userAddress.getCity());
		orderInfo.setDistrict(userAddress.getDistrict());
		orderInfo.setAddress(userAddress.getAddress());
		orderInfo.setPostcode(userAddress.getPostcode());
		orderInfo.setTel(userAddress.getTel());
		orderInfo.setMobile(userAddress.getMobile());
		//购买物品数量 
		orderInfo.setGoodsNumber(goodsNumber);

		//订单金额 （购物数量 * 商品交易金额）
		//计算价格
		ImputedPrice imputedPrice = calculatePostage(orderInfoReq);

		//订单总金额 订单金额 + 运费 - 优惠券金额
		orderInfo.setOrderTitle(orderTitle);
		orderInfo.setOrderImg(orderImg);
		orderInfo.setCouponId(orderInfoReq.getCouponId());
		orderInfo.setCouponAmount(imputedPrice.getCouponAmount());//优惠金额
		orderInfo.setOrderPayee(imputedPrice.getOrderAmount());//商品总金额
		orderInfo.setShippingPayee(imputedPrice.getPostageAmount());//邮费
		orderInfo.setTotalPayee(imputedPrice.getTotalAmount());//总金额
		//如果开发票
		if(orderInfoReq.getIsInvoice() != null && orderInfoReq.getIsInvoice() == 1){
			//发票金额 = 订单金额 - 优惠券金额
			Integer invoiceAmount = imputedPrice.getOrderAmount() - orderInfo.getCouponAmount();
			if(invoiceAmount < 0){
				invoiceAmount = 0;
			}
			orderInfo.setInvoiceAmount(invoiceAmount);
			orderInfo.setIsInvoice(orderInfoReq.getIsInvoice());
			UserInvoice ui = orderMapper.getUserInvoiceByTitle(orderInfoReq.getInvoiceTitle());
			if(ui == null){
				UserInvoice userInvoice = new UserInvoice();
				userInvoice.setUserId(orderInfoReq.getUserId());
				userInvoice.setTitle(orderInfoReq.getInvoiceTitle());
				orderMapper.createUserInvoice(userInvoice);
				orderInfo.setInvoiceId(userInvoice.getId());
			}else{
				orderInfo.setInvoiceId(ui.getId());
			}

		}else{
			orderInfo.setIsInvoice(0);
			orderInfo.setInvoiceAmount(0);
		}
		//如果订单总金额为0，则订单为已支付
		if(orderInfo.getTotalPayee() == 0){
			orderInfo.setPayStatus(OrderConstant.PAY_STATUS_PREPAID.getOrderStatus());
			orderInfo.setPayTime(DateUtils.getCurrentDate());
		}
		else{
			orderInfo.setPayStatus(OrderConstant.PAY_STATUS_NON_PAYMENT.getOrderStatus());
		}
		//买家留言
		orderInfo.setBuyerMemo(orderInfoReq.getBuyerMemo());
		//订单来源
		orderInfo.setSource(orderInfoReq.getSource());
		Date createTime = DateUtils.getCurrentDate();
		orderInfo.setExpirationTime(DateUtils.addDay(createTime, 1));
		//保存订单
		orderMapper.createOrderInfo(orderInfo);

		//保存订单发票信息
		if(orderInfoReq.getIsInvoice() != null && orderInfoReq.getIsInvoice() == 1){
			OrderInvoice orderInvoice = new OrderInvoice();
			orderInvoice.setOrderId(orderInfo.getId());
			orderInvoice.setAmount(orderInfo.getOrderPayee());
			orderInvoice.setTitle(orderInfoReq.getInvoiceTitle());
			orderMapper.createOrderInvoice(orderInvoice);
		}

		//保存订单详情
		if(orderDetails.isEmpty()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "保存订单,订单详情不能为空");
		}
		orderMapper.batchCreateOrderDetail(orderDetails,orderInfo.getId());
		OrderInfoRes oi = new OrderInfoRes();
		OrderInfoRes orderInfoRes = orderMapper.getOrderById(orderInfo.getId());
		oi.setOrderStatus(orderInfoRes.getOrderStatus());
		oi.setOrderNo(orderInfo.getOrderNo());
		oi.setId(orderInfo.getId());
		oi.setTotalPayee(orderInfo.getTotalPayee());
		return oi;
	}

	@Override
	public void cancelOrder(OrderInfoReq orderInfoReq) {

		if(orderInfoReq.getId() == null || orderInfoReq.getId() == 0){
			throw new ShopServerException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单ID不能为空");
		}
		OrderInfo orderInfo = orderMapper.getOrderById(orderInfoReq.getId());
		if(null == orderInfo){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单不存在");
		}
		if(orderInfoReq.getUserId().intValue() != orderInfo.getUserId().intValue()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "该订单不属于您,不能取消");
		}
		//已支付不能取消
		if(orderInfo.getOrderStatus() == OrderConstant.PAY_STATUS_PREPAID.getOrderStatus()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单已支付，不可取消.");
		}
		//已发货不可取消
		if(orderInfo.getOrderStatus() == OrderConstant.SHIPPING_STATUS_SHIPPED.getOrderStatus()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单已发货不可取消.");
		}
		//已收货不可取消
		if(orderInfo.getOrderStatus() == OrderConstant.SHIPPING_STATUS_RECEIVED.getOrderStatus()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单已收货不可取消.");
		}
		//已完成订单不可取消
		if(orderInfo.getOrderStatus() == OrderConstant.ORDER_STATUS_COMPLETED.getOrderStatus()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单已完成不可取消.");
		}
		//已过期不可取消
		if(orderInfo.getOrderStatus() == OrderConstant.ORDER_STATUS_EXPIRED.getOrderStatus()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单已过期不可取消.");
		}
		List<OrderDetailsRes> orderDetails = orderMapper.getOrderDetailList(orderInfoReq.getId());
		for(OrderDetailsRes or : orderDetails){
			goodsService.increaseStock(or.getGoodsId(), or.getGoodsNumber());
		}
		orderMapper.cancelOrderInfo(orderInfoReq.getId(), OrderConstant.ORDER_STATUS_CANCELED.getOrderStatus());

	}

	@Override
	public void confirmReceipt(OrderInfoReq orderInfoReq) {
		OrderInfoRes oir = orderMapper.getOrderById(orderInfoReq.getId());
		if(null == oir){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "未查询到该订单.");
		}
		if(OrderConstant.SHIPPING_STATUS_UNFILLED.getOrderStatus().intValue() == oir.getShippingStatus().intValue()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "该商品未发货.");
		}
		orderMapper.confirmReceipt(orderInfoReq.getId(), OrderConstant.ORDER_STATUS_COMPLETED.getOrderStatus(),
				OrderConstant.SHIPPING_STATUS_RECEIVED.getOrderStatus());

	}

	@Override
	public void paySuccessCallback(String orderNo, String payChannel,
			String buyerAccount, String chId) {
		// TODO Auto-generated method stub

	}

	@Override
	public ImputedPrice calculatePostage(OrderInfoReq orderInfoReq) {
		if(orderInfoReq.getOrderDetails() == null || orderInfoReq.getOrderDetails().isEmpty()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "购买商品不能为空");
		}
		ImputedPrice imputedPrice = new ImputedPrice();
		Integer orderPrice = 0;
		Integer marketPrice = 0;
		boolean isRela = false;
		boolean isPostFree = false;
		List<Goods> goodsList = new ArrayList<Goods>();
		for(OrderDetail od :  orderInfoReq.getOrderDetails()){
			if(od.getGoodsNumber() == null || od.getGoodsNumber() <= 0){
				throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "购买数量不能为空");
			}
			if(od.getGoodsId() == null){
				throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "商品ID不能为空");
			}
			Goods good = new Goods();
			GoodsRes goodsRes = goodsService.goodsDetailById(od.getGoodsId());
			if(goodsRes == null){
				throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "商品不存在");
			}
			Integer price = goodsRes.getSalePrice() * od.getGoodsNumber();
			orderPrice += price;
			Integer mPrice = goodsRes.getMarketPrice() * od.getGoodsNumber();
			marketPrice += mPrice;
			//如果需要配送,下面会判断是否有收货地址
			if(goodsRes.getIsExpress() == 1){
				isRela = true;
			}
			//校验该商品包邮
			if(null != goodsRes.getPostFree() && goodsRes.getPostFree() == 1){
				isPostFree = true;
			}
			good.setId(od.getGoodsId());
			good.setType(od.getType());
			goodsList.add(good);
		}
		imputedPrice.setOrderAmount(orderPrice);
		if(orderInfoReq.getUserAddressId() == null || orderInfoReq.getUserAddressId() == 0){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "收货地址ID不能为空");
		}
		UserAddress userAddress = userAddressService.getUserAddressById(orderInfoReq.getUserAddressId());
		if(null == userAddress){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "用户地址不存在");
		}

		PostageConfig postageConfig = goodsService.getPostageConfigByProvinceId(userAddress.getProvinceId());
		if(isPostFree){
			//包邮
			imputedPrice.setPostageAmount(0);
		}else if(postageConfig == null){
			//不在邮递范围内
			imputedPrice.setPostageAmount(0);
		}else{
			//商品价格在包邮范围内
			if(orderPrice >= postageConfig.getPinkagePrice() ){
				imputedPrice.setPostageAmount(0);
			}else{
				imputedPrice.setPostageAmount(postageConfig.getPostage());
			}
		}

		//订单总价 = 商品总价 + 运费 - 优惠券
		Integer totalAmount = imputedPrice.getOrderAmount().intValue() + imputedPrice.getPostageAmount().intValue() - imputedPrice.getCouponAmount().intValue();
		if(totalAmount < 0){
			totalAmount = 0;
		}
		imputedPrice.setTotalAmount(totalAmount);
		return imputedPrice;
	}

	@Override
	public void callWebhookPayrSuccess(String orderNo) {
		// TODO Auto-generated method stub

	}

	@Override
	public OrderInfoRes generageOrder(OrderInfoReq orderInfoReq) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<OrderInfoRes> userOrderList(OrderInfoReq orderInfoReq) {
		if(orderInfoReq.getUserId() == null){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "用户ID不能为空");
		}
		List<OrderInfoRes> list =  orderMapper.userOrderLisr(orderInfoReq);
		for(OrderInfoRes oir : list){
			oir.setOrderImg(FileStoreUtil.getBaseUrl().concat(oir.getOrderImg()));
		}
		return list;
	}

	@Override
	public List<OrderInfoRes> orderLisr(OrderInfoReq orderInfoReq) {
		List<OrderInfoRes> list =  orderMapper.orderLisr(orderInfoReq);
		for(OrderInfoRes oir : list){
			oir.setOrderImg(FileStoreUtil.getBaseUrl().concat(oir.getOrderImg()));
		}
		return list;
	}
	
	@Override
	public Integer orderLisrCount(OrderInfoReq orderInfoReq) {
		return orderMapper.orderLisrCount(orderInfoReq);
	}

	@Override
	public OrderInfoRes orderDetail(OrderInfoReq orderInfoReq) {

		if(orderInfoReq.getId() == null || orderInfoReq.getId() ==0){
			throw new ShopServerException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单ID不能为空");
		}
		OrderInfoRes order = orderMapper.getOrderById(orderInfoReq.getId());
		if(null == order){
			throw new ShopServerException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单不存在");
		}
		order.setOrderImg(FileStoreUtil.getBaseUrl().concat(order.getOrderImg()));
		//order.setOrderImg(FileStoreUtil.getBaseUrl().concat(order.getOrderImg()));
		//获取详查详情
		List<OrderDetailsRes> orderDetails = orderMapper.getOrderDetailList(orderInfoReq.getId());
		for(OrderDetailsRes odr : orderDetails){
			GoodsRes goods = goodsMapper.getGoodsDetailById(odr.getGoodsId());
			odr.setMarketPrice(goods.getMarketPrice());
			odr.setSubject(goods.getSubject());
			odr.setThumbnailImage(FileStoreUtil.getBaseUrl().concat(goods.getThumbnailImage()));
		}
		order.setOrderDetails(orderDetails);
		return order;
	}

	@Override
	public OrderInfo getOrderInfoById(Integer orderId) {

		return orderMapper.getOrderById(orderId);
	}

	@Override
	public OrderInfo checkOrderCouldPay(Integer orderId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public OrderInfoRes getOrderInfoByOrderNo(OrderInfoReq orderInfoReq) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public OrderInfoRes getOrderInfoByOrderNo(String orderNo) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public UserDefaultAddressInvoice getUserDefaultAddressInvoice(Integer userId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<OrderDetailsRes> getOrderDetailsList(Integer orderId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void webhookPayrSuccessCallBack(String orderNo, String channel, String buyerAccount, String chId) {
		orderMapper.updateOrderPaySuccessForReal(orderNo, channel, OrderConstant.PAY_STATUS_PREPAID.getOrderStatus(), chId);

	}

	/**
	 * Integer id = orderInfoReq.getId();
		Integer shippingChannel = orderInfoReq.getShippingChannel();
		String shiippingSn = orderInfoReq.getShiippingSn();
		Integer shippingStatus = 1; //0 未发货 1.已发货 2.已收货
		Date shippingTime = new Date();
	 * @param orderInfoReq
	 * @return
	 */
	@Override
	public Integer shippingOrder(OrderInfoReq orderInfoReq) {
		Integer id = orderInfoReq.getId();
		Integer shippingChannel = orderInfoReq.getShippingChannel();
		String shiippingSn = orderInfoReq.getShiippingSn();
		Integer shippingStatus = 1; //0 未发货 1.已发货 2.已收货
		Date shippingTime = new Date();
		Integer count = orderMapper.updateOrderShipping(id, shippingChannel, shiippingSn, shippingStatus, shippingTime);
		return count;
	}



}
